package server;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
/**
 * This class is responsible for parsing the incoming messages and creating a new Request instance to return to the connection handler
 * @author yariv zur
 */
public class MessageTokenizer implements Tokenizer {

	private final BufferedInputStream _is;
	private final BufferedReader in;
	StringTokenizer tok;
	private boolean _closed = false;
	StringBuilder sb;
	/**
	 * Constructor for the MessageTokenizer class
	 * @param is - the InputStream to use
	 * @throws UnsupportedEncodingException
	 */
	public MessageTokenizer (BufferedInputStream is) throws UnsupportedEncodingException {
		_is = is;
		in = new BufferedReader(new InputStreamReader(is, "UTF-8"), 1);
		sb = new StringBuilder();
		_closed = false;
	}
	/**
	 * This method parses the message in its InputStream and returns it in the form of a Request instance
	 * if the connection is closed or the tokenizer is closed, an exception is thrown
	 */
	public Request nextToken() throws IOException {
		if (!isAlive()){
			throw new IOException("tokenizer is closed");
		}
		try{
			String line;
			while(((line = in.readLine()) != null) && line.length()>0){
				sb.append(line+" ");
			}
		}catch(IOException e){
			_closed = true;
			throw new IOException("connection was terminated");
		}
		tok = new StringTokenizer(sb.toString(), " ");

		return new Request(tok, _is);
	}
	/**
	 * Check whether the tokenizer is closed
	 */
	public boolean isAlive() {
		return !_closed;
	}


}